package net.qhzw.vip.qiyu.service;


import cn.hutool.core.date.DateUtil;
import net.qhzw.vip.qiyu.dto.DispatchDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@Service
public class MailService {


    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送HTML邮件
     *
     * @throws MessagingException
     */
    //发送HTML邮件(接收前台传过来的参数:addressee 收件人地址)
    public void sendHtmlMail(String address, DispatchDto dispatchDto, String type) throws MessagingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        String nickName = null;
        try {
            nickName = MimeUtility.encodeText("青海骑遇网络科技有限公司");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        helper.setFrom(new InternetAddress(nickName + " <" + username + ">"));
        //helper.setFrom(username);
        //收件人邮件地址
        helper.setTo(address);
        //邮件主题
        helper.setSubject(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + " 加急维修工单");
        //邮件正文
        String text = null;
        if ("notice".equals(type)) {
            text = send(dispatchDto, type);
        } else {
            text = send(dispatchDto, type);
        }
        helper.setText(text, true);
        javaMailSender.send(mimeMessage);
    }


    private String send(DispatchDto dispatchDto, String type) {
        String param = "?repairUser=%s&id=%s&realName=%s&address=%s&mobile=%s&remarks=%s";
        String repairUser = dispatchDto.getRepairUser();
        Long id = dispatchDto.getId();
        String realName = dispatchDto.getRealName();
        String address = dispatchDto.getAddress();
        String mobile = dispatchDto.getMobile();
        String remarks = dispatchDto.getRemarks();
        String format = String.format(param, repairUser, id, realName, address, mobile, remarks);
        String result = null;
        if ("notice".equals(type)) {
            result = restTemplate.getForObject("http://repair-server/test/dispatch/notice?" + format, String.class);
        } else {
            result = restTemplate.getForObject("http://repair-server/test/dispatch/urgentNotice?" + format, String.class);
        }
        return result;
    }


}
